package login

import (
	"context"
	"fmt"
	"net/http"
	"strconv"
	"time"

	"2106A-zg6/baidu/gateway/internal/svc"
	"2106A-zg6/baidu/gateway/internal/types"
	"2106A-zg6/baidu/gateway/internal/util"
	"2106A-zg6/baidu/srv/baiduclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginRequest) (resp *types.Response, err error) {

	login, err := l.svcCtx.BaiduSrv.Login(l.ctx, &baiduclient.LoginRequest{
		UserName: req.Username,
		Password: req.Password,
	})
	if err != nil {
		return &types.Response{
			Msg:  err.Error(),
			Code: http.StatusAccepted,
			Data: nil,
		}, err
	}

	jwtCfg := l.svcCtx.Config.Auth
	//登陆成功 生成 token
	token, err := util.CreateToken(jwtCfg.AccessSecret, time.Now().Unix(), jwtCfg.AccessExpire, strconv.FormatInt(login.UserInfo.Id, 10))
	if err != nil {
		return nil, err
	}

	fmt.Println(token)
	fmt.Println(login)

	return &types.Response{
		Msg:  "Login successful",
		Code: http.StatusOK,
		Data: map[string]interface{}{
			"UserInfo": login,
			"Token":    token,
		},
	}, nil
}
